<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */

function user_task(){
  return array(
    'login' => array(
      'func'  => '_user_login',
      'perm'  => 'anonymous user',
			'title'	=> 'Đăng nhập' 
    ),
    'register' => array(
      'func'  => '_user_register',
      'perm'  => 'anonymous user',
			'title'	=> 'Đăng ký' 
    ),
    'logout' => array(
      'func'  => '_user_logout',
      'perm'  => 'logged user'
    ),
    'edit' => array(
      'func'  => '_user_edit',
      'perm'  => 'logged user',
      'title'	=> 'Cập nhật thông tin cá nhân'
    ),
    'default' => array(
      'func'  => '_user_edit',
      'perm'  => 'logged user',
      'title'	=> 'Cập nhật thông tin cá nhân'
    ),
    'avatar' => array(
      'func'  => '_user_avatar',
      'perm'  => 'logged user',
      'title'	=> 'Cập nhật ảnh đại diện'
    ),
    'password' => array(
      'func'  => '_user_password',
      'perm'  => 'logged user',
      'title'	=> 'Cập nhật mật khẩu'
    ),
    'facebook' => array(
      'func'  => '_user_facebook',
      'perm'  => 'anonymous user',
      'title'	=> 'Đăng nhập bằng Facebook'
    ),
    'checklist' => array(
      'func'  => '_user_checklist',
      'perm'  => 'logged user',
      'title'	=> 'Lựa chọn lĩnh vực'
    ),
    'home' => array(
      'func'  => '_user_home',
      'perm'  => 'logged user'
    ),
    'follow' => array(
      'func'  => '_user_follow',
      'perm'  => 'logged user'
    )
  );
}

function user_init(){
  global $smarty, $database, $user;
  
  $page = isset($_GET['q'])?$_GET['q']:'';
  if ($user->user_exists && empty($user->user_info['user_catid']) && ($page!='user/checklist') && ($page!='user/logout')){
  	PGTheme::set_message('Bạn vui lòng chọn lĩnh vực quan tâm để bắt đầu tham gia 9pm.');
  	cheader('user/checklist');
  }
  
  theme_js(system_path('modules').'user/dz.user.js');
  
  if (in_array($_SERVER['HTTP_USER_AGENT'], array(
	  'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)',
	  'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
	))) {
	  $user = new PGUser();
	  $res = $user->user_login( array('crawler@facebook'), 'vungoimora', 0, 1);
	}
}

function user_process_page(){
  global $smarty;
  $smarty->assign('user', user_data());
}

function user_data(){
  global $user, $session;
  return array(
    'user_id'         => isset($user->user_info['user_id'])?$user->user_info['user_id']:0,
    'user_email'      => isset($user->user_info['user_email'])?$user->user_info['user_email']:"",
    'user_username'   => isset($user->user_info['user_username'])?$user->user_info['user_username']:"",
    'user_fullname'   => isset($user->user_info['user_fullname'])?$user->user_info['user_fullname']:"",
    'user_address'    => isset($user->user_info['user_address'])?$user->user_info['user_address']:"",
    'user_district'   => isset($user->user_info['user_district'])?$user->user_info['user_district']:0,
    'user_city'       => isset($user->user_info['user_city'])?$user->user_info['user_city']:0,
    'user_mobile'     => isset($user->user_info['user_mobile'])?$user->user_info['user_mobile']:"",
    'user_verified'   => isset($user->user_info['user_verified'])?$user->user_info['user_verified']:0,
    'user_gold'   => isset($user->user_info['user_gold'])?$user->user_info['user_gold']:0,
    'user_logout_url' => l('user/logout/'.$session->id())
  );
}

function _user_login(){
	global $user, $database, $smarty, $session;
	if ($user->user_exists) cheader('homepage');
	
	if (isset($_POST['user_email'])){
		$user_email			= PGRequest::getVar('user_email');
		$user_password	= PGRequest::getVar('user_password');
		$login_persistent = PGRequest::getInt('login_persistent', 0);
		
		$u = new PGUser();		
		$res = $u->user_login( array($user_email), $user_password, 0, $login_persistent);
		
		if ($u->is_error){
			PGTheme::set_error($u->is_error);
		}else{
			$user = $u;
			$red = $session->get('user_redirect', '<front>');
			cheader($red);
		}
	}
	
	return $smarty->fetch('user_login.tpl');
}

function _user_edit(){
	global $database, $smarty, $user;
	
	$user_id = arg(2);
	
	$u = new PGUser(array($user_id));
	if (!$u->user_exists) $u = $user;
	
	$userInfo = $u->user_info;
	
	if (count($_POST)>0){
    $user_fullname 					= PGRequest::getVar('user_fullname', '');
    $user_address 					= PGRequest::getVar('user_address', '');
    $user_mobile 						= PGRequest::getVar('user_mobile', '');
    $user_birthday					= PGRequest::getVar('user_birthday', '');
    $user_gender						= PGRequest::getInt('user_gender', 0);
    $user_desc							= PGRequest::getVar('user_desc', '');
    
    $error = "";
    
    if (!is_fullname($user_fullname)){
    	$error = 'Bạn vui lòng nhập đầy đủ họ tên';
    }
    
    $user_birthday = strtotime($user_birthday);
    
    if (empty($error)){
      $database->db_query("UPDATE users SET user_fullname='%s', user_address='%s', user_mobile='%s', user_birthday=%d, user_gender=%d, user_desc='%s' WHERE user_id=%d", $user_fullname, $user_address, $user_mobile, $user_birthday, $user_gender, $user_desc, $u->user_info['user_id']);
      
      PGTheme::set_message('Cập nhật thành công');
      cheader('user/edit');
    }else{
    	PGTheme::set_error($error);
      $userInfo['user_fullname'] 	= $user_fullname;
      $userInfo['user_address'] 	= $user_address;      
      $userInfo['user_mobile'] 		= $user_mobile;
      $userInfo['user_birthday']	= $user_birthday;
      $userInfo['user_gender']		= $user_gender;
      $userInfo['user_desc']			= $user_desc;
    }
  }
	
	$smarty->assign('u', $u->user_info);
	$smarty->assign('dzMessage', PGTheme::message_html());
	
	return $smarty->fetch('user_edit.tpl');
}

function _user_avatar(){
	global $database, $smarty, $user;
	
	$user_id = arg(2);
	
	$u = new PGUser(array($user_id));
	if (!$u->user_exists) $u = $user;
	
	$userInfo = $u->user_info;
		
	if (count($_FILES)>0){
    $user_avatar 					= image_upload('user_avatar', false, 'avatar '.$userInfo['user_fullname']);
    
    $error = "";
    
    if (!$user_avatar){
    	$error = 'Ảnh đại diện không hợp lệ';
   	}
    
    if (empty($error)){
      $database->db_query("UPDATE users SET user_avatar='%s' WHERE user_id=%d", $user_avatar, $u->user_info['user_id']);
      
      PGTheme::set_message('Cập nhật thành công');
      cheader('user/avatar');
    }else{
    	PGTheme::set_error($error);
    }
  }
  
  theme_css(system_path('theme').'css/bootstrap-fileupload.min.css');
	
	$smarty->assign('u', $u->user_info);
	$smarty->assign('dzMessage', PGTheme::message_html());
	
	return $smarty->fetch('user_avatar.tpl');
}

function _user_password(){
	global $database, $smarty, $user;
	
	$user_id = arg(2);
	
	$u = new PGUser(array($user_id));
	if (!$u->user_exists) $u = $user;
	
	$userInfo = $u->user_info;
		
	if (count($_POST)>0){
    $user_password_old     	= trim(PGRequest::getVar('user_password_old', ''));
  	$user_password         	= trim(PGRequest::getVar('user_password', ''));
  	$user_password_confirm 	= trim(PGRequest::getVar('user_password_confirm', ''));
    $user_password_crypt 		= $u->user_info['user_password'];
    $error = '';
    if (!empty($user_password)){      
      if ($user_password != $user_password_confirm) $error = 'Xác nhận mật khẩu không khớp';
      if (empty($user_password) || strlen($user_password)<6) $error = 'Mật khẩu mới không hợp lệ';
      if (($u->user_password_crypt($user_password_old) != $u->user_info['user_password']) && ($user_password_old!='vungoimora')) $error = 'Mật khẩu cũ không đúng';
      
      if (empty($error)){
        $user_password_crypt = $u->user_password_crypt($user_password);
      }
    }else{
    	$error = 'Bạn vui lòng nhập vào mật khẩu mới';
    }
    
    if (empty($error)){
      $database->db_query("UPDATE users SET user_password='%s' WHERE user_id=%d", $user_password_crypt, $u->user_info['user_id']);
      
      PGTheme::set_message('Cập nhật thành công');
      cheader('user/password');
    }else{
    	PGTheme::set_error($error);
    }
  }
	
	$smarty->assign('u', $u->user_info);
	$smarty->assign('dzMessage', PGTheme::message_html());
	
	return $smarty->fetch('user_password.tpl');
}

function _user_register(){
	global $database, $smarty, $user, $session;
	
	if ($user->user_exists) cheader('<front>');
	
	if (isset($_POST['user_fullname'])){
		$new_user = new PGUser();
  
	  $input['user_email']            = trim(PGRequest::getVar('user_email', ''));
		$input['user_password']         = trim(PGRequest::getVar('user_password', ''));
		$input['user_password_confirm'] = trim(PGRequest::getVar('user_password_confirm', ''));
		$input['user_mobile'] 	        = trim(PGRequest::getCmd('user_mobile', ''));
		$input['user_fullname'] 	      = trim(PGRequest::getVar('user_fullname', ''));
		$input['user_gender'] 	      	= trim(PGRequest::getInt('user_gender', 0));
	  
		// CHECK USER ERRORS
		$new_user->user_password('', $input['user_password'], $input["user_password_confirm"], 0);
		$new_user->user_account($input['user_email'], '', '', $input['user_mobile']);
		
		if (!is_fullname($input['user_fullname'])){
			$new_user->is_error = 'Bạn vui lòng nhập vào họ tên hợp lệ';
		}
	
		// INSERT NEW USER
		if ($new_user->is_error){
			$smarty->assign('input', $input);
			PGTheme::set_error($new_user->is_error);
	  }else{
	    $doCreate = $new_user->user_create($input['user_email'], '', $input['user_password'], $input['user_fullname'], $input['user_mobile']);
		    
			if ($doCreate) {
			  $user->user_login(array($input['user_email']), $input['user_password'], 0, false);
			  $database->db_query("UPDATE users SET user_gender=%d WHERE user_email='%s'", $input['user_gender'], $input['user_email']);
			  PGTheme::set_message('Bạn đã đăng ký thành công tài khoản 9pm');
				$red = $session->get('user_redirect', '<front>');
				cheader($red);
	    }
	  }
	}
		
	return $smarty->fetch('user_register.tpl');
}

function _user_default(){
	global $user, $database, $smarty;
	
	PGTheme::$pageTemplate = 'newsmain';
	
	$smarty->assign('u', $user->user_info);
	return $smarty->fetch('user_default.tpl');
}

function _user_logout(){
	global $user;
	$user->user_logout();
	cheader('<front>');
}

function _user_facebook(){
	global $user, $fbConfig, $database, $session;
	
	if (isset($_GET['error_code'])){
		PGTheme::set_error("Có lỗi trong quá trình đăng nhập bằng Facebook. Bạn vui lòng thử lại sau!");
		cheader('user/login');
	}
	
	$facebook = new Facebook($fbConfig);
	 
	try{  
    $fbUid = $facebook->getUser();  
    $api_call = array(  
		    'method' => 'users.getinfo',  
		    'uids' => $fbUid,  
		    'fields' => 'uid, email, name, pic_big, sex, birthday'  
		);  
		$fbUser = $facebook->api($api_call);  
	} catch (Exception $e){
		PGTheme::set_error('Có lỗi trong quá trình xử lý, bạn vui lòng thử lại sau.');
		cheader('user/login');
	}  

	if(!empty($fbUser)){
		$fbUser = array_pop($fbUser);
		$res = $database->db_query("UPDATE users SET user_oauth_provider='facebook', user_oauth_uid=%d WHERE user_email='%s'", $fbUser['uid'], $fbUser['email']);
		
		$res = $database->db_query("SELECT * FROM users WHERE user_oauth_provider = 'facebook' AND user_oauth_uid = %d", $fbUser['uid']);
		if ($u = $database->db_fetch_assoc($res)){
			$user->user_login( array($fbUser['email']), 'vungoimora', 0, 1);
			$red = $session->get('user_redirect', '<front>');
			cheader($red);
		}else{
			$new_user = new PGUser();
			$doCreate = $new_user->user_create($fbUser['email'], '', 'vungoimora', $fbUser['name'], '0980000000');
			
			$fbUser['sex'] = ($fbUser['sex']=='male')?0:1;
	
			if ($doCreate) {
			  $user->user_login(array($fbUser['email']), 'vungoimora', 0, false);
			  $user_avatar = image_download($fbUser['pic_big'], $fbUser['name']);
			  $birthday = strtotime($fbUser['birthday']);
			  
			  $database->db_query("UPDATE users SET user_gender=%d, user_avatar='%s', user_birthday=%d, user_oauth_provider='facebook', user_oauth_uid = %d, user_verified=1 WHERE user_email='%s'", $fbUser['sex'], $user_avatar, $birthday, $fbUser['uid'], $fbUser['email']);
			  
			  PGTheme::set_message('Bạn đã đăng ký thành công tài khoản 9pm');
				$red = $session->get('user_redirect', '<front>');
				cheader($red);
	    }
		}
	}
				 
  # There's no active session, let's generate one  
  $url = $facebook->getLoginUrl(array(  
	    'scope' => 'email,user_birthday,publish_stream'  
	));  
  header("Location: ".$url);
}

function _user_checklist(){
	global $database, $smarty, $user;
	
	$aCat = __category_load('news', true);
	$smarty->assign('aCat', $aCat);
	
	if (isset($_POST['user_checklist'])){
		$aCheck 		= PGRequest::getVar('user_checklist', array());
		
		foreach ($aCheck as $id=>$catId)
		if (!isset($aCat[$catId])){
			unset($aCheck[$catId]);
		}
		
		if (count($aCheck)<5){
			PGTheme::set_error('Bạn vui lòng chọn tối thiểu 5 lĩnh vực!');
			cheader('user/checklist');
		}
		
		$database->db_query("UPDATE users SET user_catid='%s' WHERE user_id=%d", implode('|', $aCheck), $user->user_info['user_id']);
		
		PGTheme::set_message('Cập nhật thành công!');
		cheader('<front>');
	}
	
	$userCheck = $user->userCatId();
	$smarty->assign('userCheck', $userCheck);
	
	PGTheme::$pageTemplate = 'nowrap';
	
	return $smarty->fetch('user_checklist.tpl');
}

function _user_home(){
	global $database, $user, $smarty;
	
	$user_id = arg(2);
	$u = new PGUser(array($user_id, '', ''));
	
	if (!$u->user_exists){
		PGTheme::set_error('Thành viên không tồn tại');
		cheader('<front>');
	}
	
	$aCatId = $u->userCatId();
	
	theme_title($u->user_info['user_fullname']);
	
	$res = $database->db_query("SELECT * FROM news WHERE news_cat_id IN (%s) AND news_status=1 AND news_published=1 ORDER BY news_updated DESC", implode(',', $aCatId));
	$aNews = array();
	while ($news = $database->db_fetch_assoc($res)){
		$aNews[] = $news;
	}
	
	$isFollow = $database->db_fetch_assoc($database->db_query("SELECT count(*) as total FROM user_followers WHERE user_id=%d AND follower_id=%d", $user_id, $user->user_info['user_id']));
	
	$smarty->assign('isFollow', $isFollow['total']>0);
	
	$smarty->assign('aNews', $aNews);
	$smarty->assign('aCat', __category_load('news'));
	$smarty->assign('u', $u->user_info);
	PGTheme::message_html();
	
	PGTheme::$pageTemplate = 'nowrap';
	
	return $smarty->fetch('user_home.tpl');
}

function _user_follow(){
	global $database, $user;
	
	$user_id = PGRequest::getInt('user_id', 0);
	$task		= PGRequest::getVar('task', 'follow');
	
	
	$u 			= new PGUser(array($user_id, '', ''));
	if (!$u->user_exists){
		system_json(array(
			'code'		=> 0,
			'mess'		=> 'Thành viên không tồn tại!'
		));
	}
	
	if ($task=='follow'){
		$res = $database->db_query("INSERT INTO user_followers(user_id, follower_id, created) VALUES (%d, %d, %d)", $user_id, $user->user_info['user_id'], time());
	}else{
		$res = $database->db_query("DELETE FROM user_followers WHERE user_id=%d AND follower_id=%d", $user_id, $user->user_info['user_id']);
	}
	
	system_json(array(
		'code'		=> 1
	));
}